package com.lagou.filter;

import com.alibaba.fastjson.JSONObject;
import com.lagou.util.IpRateCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * IP注册接口的防爆刷过滤器
 */
@Slf4j
@Component
@RefreshScope //支持配置文件动态刷新
public class IpLimitFilter implements GlobalFilter, Ordered {

    //统计时间值，最近x分钟内
    @Value("${ipLimit.X}")
    private Integer x;

    //阈值，不能超过y次
    @Value("${ipLimit.Y}")
    private Integer y;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        URI uri = request.getURI();

        //只检查注册接口防爆刷，其他请求不过滤
        if (!uri.getPath().contains("/user/register/")) {
            return chain.filter(exchange);
        }

        String ip = request.getRemoteAddress().getAddress().getHostAddress();

        //统计当前ip请求频率，判断是否超过阈值
        boolean isOutThreshold = IpRateCountUtil.checkIpRateThreshold(ip, x, y);

        //当请求频率超过阈值，返回错误提示
        if (isOutThreshold) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", "403");
            jsonObject.put("message", "您频繁进行注册，请求已被拒绝");
            DataBuffer wrap = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
